package com.Cfeng.XiaohuanChat.session;

import com.Cfeng.XiaohuanChat.domain.Resp;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;

/**
 * @author Cfeng
 * @date 2022/8/21
 * 这个sessin的监听器就放在session包下面了，监听的是sessin的sessinInfo失效的事件
 */

@RequiredArgsConstructor
public class SessionInfoExiredStrategy implements SessionInformationExpiredStrategy {
    //处理对象转化的mapper，jackson工具将对象转为JSON格式,自动配置了对象
    private final ObjectMapper objectMapper;

    //失效异常信息处理, 这里直接返回信息，查询到失效的session证明到达并发上限
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        //返回异常信息
        event.getResponse().setContentType("application/json;charset=utf-8");
        event.getResponse().getWriter().write(objectMapper.writeValueAsString(Resp.failed("已达到并发上限")));
    }
}
